Posted by: Cirilo Meggiolaro | 05/10/2009

Tip of the day #208 – ASP.NET MVC – Populating dropdownlists using LINQ to SQL

Due to some e-mails I’ve received this week I am posting a quick tip on how to populate an ASP.NET MVC dropdownlist control using LINQ to SQL. If you haven’t read the Tip#189 about ASP.NET MVC dropdownlist controls, it is a good time to read it.

How to

Create a new ASP.NET MVC Web Application;

Right-click on the Models folder and select Add > New Item;

From the Add New Item dialog, select LINQ to SQL classes. Name it MyModel.dbml and click Add;

Picture 1 - Create a new LINQ to SQL file

Picture 1 - Create a new LINQ to SQL file

Select the connection you want to use on the Server Explorer Window, expand it and select the tables you want to use;

Drag and drop them onto the dbml file surface. For this example I am using a database that has two tables: Product and Category;

Picture 2 - Product and categories tables added to the dbml file

Picture 2 - Product and categories tables added to the dbml file

Right-click the Controllers folder and select Add > Controller. Name it ProductController and hit the Add button;

Picture 3 - New controller class

Picture 3 - New controller class

A new controller class is created it. Open it. We are going to add an action method called Selector that will perform a LINQ query to retrieve a list of products. We are going to save it to the ViewData dictionary and request a view to be rendered;

public class ProductController : Controller
{
    MyModelDataContext _ctx = new MyModelDataContext();

    public ActionResult Selector()
    {
        var products = from prod in _ctx.products
                                select prod;

        ViewData[“ProductList”] = products;

        return View();
    }
}

Right-click the action method we’ve just created and select Add View (or just press ctrl + M, V). On the Add View dialog, name it Selector and keep the first two checkboxes unchecked. Hit the Add button;

Picture 4 - Create the View for our selector

Picture 4 - Create the View for our selector

On the View we are going to use the DropdownList HtmlHelper method to render the dropdownlist control using the list of products added to the ViewData dictionary by our Selector action method. The object used to bind an IEnumerable object to a dropdownlist control is the SelectList. There an explanation about it on Tip #189. We are going also to add a submit button so we can catch the selected item on the controller class. The Html markup will be similar to the following:

<% using (Html.BeginForm()) { %>
    <%= Html.DropDownList(“lstProducts”, new         SelectList((IEnumerable)ViewData[“ProductList”], “ID”, “Name”)) %>
    <input type=”submit” value=”Submit” />
<% } %>

Let’s add an action method that handles the post actions on this view so we can catch the selected product id:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Selector(FormCollection form)
{
    /// Gets the selected product.
    int productID = Convert.ToInt32(form[“lstProducts”]);

    […]
}

Build and run the application. Navigate to http://localhost:<Port Number>/Product/Selector . The dropdownlist control is loaded and displays the product name.

Picture 5 - The product selector in action

Picture 5 - The product selector in action

You may hit the submit button and check the product id on the Selector action method that handles the post action.

It is just a simple example on how to populate the dropdownlist control using LINQ to SQL. Keep in mind that performing queries directly on the controller is not a good practice and tie your application to a specific data source is not maintainable. Check the posts below on how to make you application loosely coupled and how to create a service layer for your application:


Responses

  1. thanks Cirilo. Keep posting.

  2. i think that in controller u must user SelectList object and then put it in ViewDate like:

    ViewData[“ProductList”] = new SelectList(products, “ID”, “Name”);

    and in your view simple user of dropdown like:

    the main idea that u will not use any logic in your views

  3. Cirilo – have you any suggestion about how to show the selected item from the list in the case where this view is an Edit view?

  4. This code is really effective, I got success to populate my dropdown list perfectly.

    Thank you

  5. Thanks It was an very useful tip


Leave a comment

Categories